package org.unisinos.gc.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.unisinos.gc.dao.ArtigoDAO;
import org.unisinos.gc.dao.AutorDAO;
import org.unisinos.gc.dao.CoautorDAO;
import org.unisinos.gc.dao.SubAreaDAO;
import org.unisinos.gc.dao.UtilDAO;
import org.unisinos.gc.exception.GCValidationException;
import org.unisinos.gc.form.ArtigoForm;
import org.unisinos.gc.util.FileUtil;
import org.unisinos.gc.validation.ArtigoValidation;
import org.unisinos.gc.vo.Artigo;
import org.unisinos.gc.vo.Autor;
import org.unisinos.gc.vo.Usuario;

public class AddArtigoAction extends Action {
	
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		ActionErrors errors = new ActionErrors();
		ActionForward forward = null;
		ArtigoForm artigoForm = null;
		try {
			super.execute(mapping, form, request, response);

			artigoForm = (ArtigoForm) form;
			Artigo artigo = artigoForm.toArtigo();
			String erro = ArtigoValidation.validaSaveNew(artigo);
			if (StringUtils.isEmpty(erro)) {
				artigo.setCodigo(UtilDAO.getNextCodigo("artigo", "codigo"));
				Autor autor = new Autor();
				Usuario user = (Usuario) request.getSession().getAttribute(
						"usuarioLogado");
				autor.setCodigo(user.getAutor());
				artigo.setAutor(autor);
				ArtigoDAO.addArtigo(artigo);
				CoautorDAO.updateCoautoresByArtigo(artigo.getCodigo(), artigoForm.getCodCoautores());
				
				//copiando arquivo pro servidor
				if (artigo.getFile() != null) {
					FileUtil.copyFile(artigo.getFile());
				}

				forward = mapping.findForward("success");
			} else {
				errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("artigo.error", erro));
			}
		} catch (GCValidationException gcve) {
			gcve.printStackTrace();
			errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("artigo.error", gcve.getMessage()));
		} catch (Exception e) {
			e.printStackTrace();
			errors.add(ActionErrors.GLOBAL_ERROR,
					new ActionError("systemError"));
		} finally {
			Usuario user = (Usuario) request.getSession().getAttribute("usuarioLogado");
			artigoForm.setAutores(AutorDAO.getAutorListIgnoring(user.getAutor()));
			request.setAttribute("subAreaList", SubAreaDAO.getSubAreaListOrdered(user.getCongresso()));
		}

		if (!errors.isEmpty()) {
			super.saveErrors(request, errors);
			forward = mapping.findForward("error");
			request.setAttribute("mode", "new");
		}

		return forward;
	}

}
